<template>
  <div class="log-container">
    <el-form :inline="true" size="mini"
      ref="searchForm" label-width="60px"
      :model="searchForm"
    >
      <el-form-item label="登录名">
        <el-input v-model="searchForm.loginName" placeholder="请输入登录名" />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="searchForm.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          clearable
          v-model="searchForm.isEnable"
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in enums.IS_ENABLE"
            :key="item.code"
            :label="item.label"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="doSearch"
          >搜索</el-button
        >
        <el-button
          type="default"
          size="mini"
          icon="el-icon-refresh"
          @click="resetSearch"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="searchs-content">
      <el-button
        type="primary"
        size="mini"
        plain
        icon="el-icon-plus"
        @click="addDialog"
        >新增</el-button
      >
    </div>
    <Table
      :tableHeader="tableHeader"
      :tableData="tableData"
      :tableLoading="listLoading"
    >
      <template slot="enableStatus" slot-scope="scope">
        <el-switch
          v-model="scope.row.isEnable"
          :active-value="1"
          :inactive-value="0"
          @change="isEnabled($event, scope.row)"
        >
        </el-switch>
      </template>
      <template slot="action" slot-scope="scope">
        <el-button type="primary" size="mini" @click="addDialog(scope.row)"
          >详情</el-button
        >
        <el-button type="info" class="reset-btn" size="mini" @click="resetDialog(scope.row)"
          >重置密码</el-button
        >
        <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </Table>
    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="searchForm.pageNum"
      :limit.sync="searchForm.pageSize"
      @pagination="fetchData"
    />

    <!-- 新增弹框 -->
    <Dialog
      :visible="visible"
      width="30%"
      :isFooter="false"
      :title="'人员' + dialogTitle"
      @cancelDialog="cancelDialog"
    >
      <AddUser :dialogForm="dialogForm" @cancelDialog="cancelDialog"></AddUser>
    </Dialog>

    <!-- 重置密码弹框 -->
    <Dialog
      :visible="resetVisible"
      width="30%"
      title="修改密码"
      @confirmDialog="resetConfirm"
      @cancelDialog="resetCancel"
    >
      <el-form
        ref="resetForm"
        :model="resetForm"
        :rules="resetRules"
        label-width="80px"
        class="resetForm"
      >
        <el-form-item label="新密码" prop="newPwd">
          <el-input
            v-model="resetForm.newPwd"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="renewPwd">
          <el-input
            v-model="resetForm.renewPwd"
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { Users } from "@/api/system";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import AddUser from "./addUser.vue";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";

import { mapState } from "vuex";

export default {
  components: { Pagination, Table, Dialog, AddUser },
  data() {
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入新密码"));
      } else {
        if (this.resetForm.newPwd !== value) {
          callback(new Error("两次密码输入不一致"));
        }
      }
      callback();
    };
    return {
      listLoading: true,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        loginName: "",
        userName: "",
        isEnable: null,
      },

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        {
          label: "用户id",
          prop: "id",
        },
        {
          label: "登录名",
          prop: "loginName",
        },
        {
          label: "手机号",
          prop: "phone",
        },
        {
          label: "用户名",
          prop: "userName",
        },
        { slot: "enableStatus", label: "启用状态", width: "80" },
        {
          label: "创建人",
          prop: "createBy",
        },

        {
          label: "创建时间",
          prop: "createTime",
        },
        { slot: "action", label: "操作", width: "320" },
      ],
      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        userName: "",
        loginName: "",
        password: "123456",
        phone: "",
        type: "",
      },

      dialogBtnLoading: false,

      currentRow: {},
      dialogTitle: "",
      // 重置密码
      resetVisible: false,
      resetForm: {
        newPwd: "",
        renewPwd: "",
      },
      resetRules: {
        newPwd: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 20, message: "长度在6到20个字之间", trigger: "blur" },
        ],
        renewPwd: [{ required: true, validator: validatePass }],
      },
    };
  },
  computed: {
    ...mapState({ enums: (state) => state.enums.enums }),
  },
  async created() {
    this.fetchData();
  },
  methods: {
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
      this.listLoading = true;
      this.tableData = [];
      this.total = 0;
      Users("/list", { ...removeNullUndefined(this.searchForm) })
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 弹框取消
    cancelDialog(type) {
      this.visible = false;
      this.clearData();
      if (type) {
        this.fetchData();
      }
    },
    clearData() {
      this.dialogForm = {
        userName: "",
        loginName: "",
        password: "123456",
        phone: "",
        type: "",
      };
    },

    // 新增
    async addDialog(row) {
      this.visible = true;
      this.clearData();
      if (row.id) {
        this.dialogTitle = "详情";
        this.dialogForm = { ...row };
      } else {
        this.dialogTitle = "新增";
      }
    },
    handleDelete(row) {
      handleConfirm("删除后不可恢复，确定继续？", "warning", "提示")
        .then((res) => {
          this.doDelete(row);
        })
        .catch((err) => {});
    },
    doDelete(row) {
      Users(`/${row.id}`, {}, "delete").then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.resetSearch();
          this.fetchData();
        }
      });
    },
     // 是否启用
     isEnabled(e, row) {
      if (e == 1) {
        row.isEnable = 0;
      } else {
        row.isEnable = 1;
      }
      let msg =
        row.isEnable === 1
          ? `<span style='color:red'>当前操作会影响用户的正常功能使用，确定要停用吗？</span>`
          : `<span style='color:red'>确定要启用该用户吗？</span>`;

      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true,
        type: "warning",
      }).then(() => {
        this.doEnabled(row);
      });
    },
    // 停用/启用
    doEnabled(row) {
      let url = row.isEnable == 1 ? "/disable" : "/enable";
      Users(`${url}/${row.id}`, {}, "put").then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },

    resetSearch() {
      this.searchForm = {
        pageNum: 1,
        pageSize: 15,
        loginName: "",
        userName: "",
        isEnable: null,
      };
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },
    resetConfirm() {
      this.$refs["resetForm"].validate((valid) => {
        if (valid) {
          handleConfirm("确定要重置密码吗？", "warning", "提示")
            .then((res) => {
              this.doEditPassword();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    doEditPassword() {
      Users(
        `/reset/password/${this.currentRow.id}?newPassword=${this.resetForm.newPwd}`,
        {},
        "put"
      ).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.resetVisible = false;
        }
      });
    },
    resetCancel() {
      this.resetVisible = false;
      if (typeof this.$refs["resetForm"] !== "undefined") {
        this.$refs["resetForm"].resetFields();
      }
    },
    resetDialog(row) {
      this.resetVisible = true;
      this.currentRow = row;
      if (typeof this.$refs["resetForm"] !== "undefined") {
        this.$refs["resetForm"].resetFields();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.log-container{
  background-color: #ffffff;
  margin: 20px;
  padding-top: 10px;
  border-radius: 12px;
}
.ipt {
  width: 96%;
}
.reset-btn{
  background: #95a2b7;
}
</style>
